package com.diyunapp.xilinapp.details;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.OrderOuterAdapter;
import com.diyunapp.xilinapp.bean.AddressBean;
import com.diyunapp.xilinapp.bean.FaPiaoBean;
import com.diyunapp.xilinapp.bean.ManSongBean;
import com.diyunapp.xilinapp.bean.OrderGoodsInBean;
import com.diyunapp.xilinapp.bean.OrderGoodsOutBean;
import com.diyunapp.xilinapp.bean.ParamsBean;
import com.diyunapp.xilinapp.bean.YouHuiQuanBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.OrderMoneyChageInterface;
import com.diyunapp.xilinapp.myindent.WaitPayDetailActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarActivity;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.diyunapp.xilinapp.utils.ScrollListViewDisplay;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/23.
 */
public class OrderConfirmActivity extends StatusBarActivity implements View.OnClickListener {

    @Bind(R.id.order_confirm_goback_ib)
    ImageButton orderConfirmGobackIb;
    @Bind(R.id.order_username_tv)
    TextView orderUsernameTv;
    @Bind(R.id.order_userphone_tv)
    TextView orderUserphoneTv;
    @Bind(R.id.order_useradress_tv)
    TextView orderUseradressTv;
    @Bind(R.id.order_changeinfo_ib)
    ImageButton orderChangeinfoIb;
    @Bind(R.id.order_useradress_ll)
    LinearLayout orderUseradressLl;
    @Bind(R.id.no_address_ll)
    LinearLayout noAddressLl;
    @Bind(R.id.pay_offline_rb)
    RadioButton payOfflineRb;
    @Bind(R.id.pay_offline_view)
    View payOfflineView;
    @Bind(R.id.pay_online_rb)
    RadioButton payOnlineRb;
    @Bind(R.id.paytype_select_rg)
    RadioGroup paytypeSelectRg;
    @Bind(R.id.xilinbi_paynum_rb)
    CheckBox xilinbiPaynumRb;
    @Bind(R.id.use_xilinbi_bt)
    TextView useXilinbiBt;
    @Bind(R.id.input_xilinbi_et)
    EditText inputXilinbiEt;
    @Bind(R.id.xilinbi_money_et)
    TextView xilinbiMoneyEt;
    @Bind(R.id.use_xilinbi_ll)
    LinearLayout useXilinbiLl;
    @Bind(R.id.chargecard_paynum_rb)
    CheckBox chargecardPaynumRb;
    @Bind(R.id.accountmoney_paynum_rb)
    CheckBox accountmoneyPaynumRb;
    @Bind(R.id.input_tradecode_et)
    EditText inputTradecodeEt;
    @Bind(R.id.input_tradecode_bt)
    TextView inputTradecodeBt;
    @Bind(R.id.input_tradecode_ll)
    LinearLayout inputTradecodeLl;
    @Bind(R.id.fapiao_get_rb)
    CheckBox fapiaoGetRb;
    @Bind(R.id.myfapiao_tv)
    TextView myfapiaoTv;
    @Bind(R.id.change_myfapiao_ib)
    ImageButton changeMyfapiaoIb;
    @Bind(R.id.myfapiao_ll)
    LinearLayout myfapiaoLl;
    @Bind(R.id.order_stores_listview)
    ListView orderStoresListview;
    @Bind(R.id.orderconfirm_atlast_price_tv)
    TextView orderconfirmAtlastPriceTv;
    @Bind(R.id.commit_order_tv)
    TextView commitOrderTv;

    private String loginKey = "d27d6a1b8abec70888744a6b39d9c635";
    private String cart_id;
    private String ifcart;

    //是否支持货到付款
    private String ifshow_offpay = "null";
    private String allow_offpay = "";
    //运费hash，选择地区时作为参数提交
    private String freight_hash;
    private HashMap<String,String> yunfeiHash = new HashMap<>();

    //选择的支付方式
    private String pay_name = "";
    //订单总金额
    private float order_total_money = 0;
    private float last_xilinbi_money = 0;
    private float last_yhq_money = 0;

    //提交后生成的订单编号
    private String pay_sn = "";

    //用户地址
    private AddressBean.DatasBean.AddressListBean myAddress;
    private AddressBean.DatasBean.AddressListBean changedAddressTemp;
    private String offpay_hash;
    private  String offpay_hash_batch;

    //已选购的商品部分
    private List<OrderGoodsOutBean> myGoodsList;
    private OrderOuterAdapter myGoodsAdapter;

    //充值卡和预付款
    private float available_predeposit = 0;//可用预存款
    private float available_rc_balance = 0;//可用充值卡
    private boolean useCharge = false;
    private int useAccount = 0;
    private boolean codeCertify = false;

    //希霖币
    private int max_use_xlb = 0;//本单可用希霖币数量
    private int xlb_dis = 1;//希霖币抵扣金额的比例
    private int member_xlb = 0;//用户希霖币数量
    private int xinlinbi_max = 0; //最大可用的希霖币数量
    private int set_xlb_num = 0;  //用户设置的最终使用希霖币的个数
    private float xlb_dis_money = 0;//用户设置的最终使用希霖币抵扣的金额

    //发票内容
    private String vat_hash;//发票信息hash
    private FaPiaoBean myFapiao;
    private boolean ifGetFapiao = false;

    private View headView;

    private boolean ifgetorder = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_confirm_layout);
        ButterKnife.bind(this);
        loginKey = MainActivity.myLogin.getLoginkey();
        cart_id = getIntent().getStringExtra("CardId");
        ifcart = getIntent().getStringExtra("IfCart");
        initViews();
        getGoodsList();
    }

    private void initViews() {
        headView = findViewById(R.id.order_confirm_menubar_inc);
        //super.MenuWidget(headView);

        orderConfirmGobackIb.setOnClickListener(this);
        //地址设置控件
        orderChangeinfoIb.setOnClickListener(this);
        noAddressLl.setOnClickListener(this);

        //希霖币控件
        xilinbiPaynumRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    useXilinbiLl.setVisibility(View.VISIBLE);
                } else {
                    order_total_money += xlb_dis_money;
                    orderconfirmAtlastPriceTv.setText("￥" + order_total_money);
                    //退回后需要将两个参数清零，防止反复点击操作
                    xlb_dis_money = 0;
                    last_xilinbi_money = 0;
                    useXilinbiLl.setVisibility(View.GONE);
                }
            }
        });

        useXilinbiBt.setOnClickListener(this);

        //购买商品控件
        myGoodsList = new ArrayList<>();
        myGoodsAdapter = new OrderOuterAdapter(myGoodsList, this, new OrderMoneyChageInterface() {
            @Override
            public void changeTotalMoney(float money) {
                order_total_money += last_yhq_money;
                order_total_money -= money;
                orderconfirmAtlastPriceTv.setText("￥" + order_total_money);
                last_yhq_money = money;
            }
        });
        orderStoresListview.setAdapter(myGoodsAdapter);

        //支付方式选择
        paytypeSelectRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Log.i("zhangxiaoxidebug","changed checkedId =  "+ checkedId);
                if (checkedId == R.id.pay_online_rb) {
                    pay_name = "online";
                    if(xinlinbi_max>0)
                    {
                        xilinbiPaynumRb.setVisibility(View.VISIBLE);
                    }
                    if(available_rc_balance>0)
                    {
                        chargecardPaynumRb.setVisibility(View.VISIBLE);
                    }

                    if(available_predeposit>0)
                    {
                        accountmoneyPaynumRb.setVisibility(View.VISIBLE);
                    }
                } else {

                    pay_name = "offline";
                    xilinbiPaynumRb.setVisibility(View.GONE);
                    useXilinbiLl.setVisibility(View.GONE);
                    chargecardPaynumRb.setVisibility(View.GONE);
                    accountmoneyPaynumRb.setVisibility(View.GONE);
                    inputTradecodeLl.setVisibility(View.GONE);
                }
            }
        });

        //充值卡控件
        chargecardPaynumRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    useCharge = true;
                    inputTradecodeLl.setVisibility(View.VISIBLE);
                } else {
                    useCharge = false;
                    if (useAccount<1) {
                        inputTradecodeLl.setVisibility(View.GONE);
                    }
                }
            }
        });

        //预存款使用控件
        accountmoneyPaynumRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    useAccount = 1;
                    inputTradecodeLl.setVisibility(View.VISIBLE);
                } else {
                    useAccount = 0;
                    if (!useCharge) {
                        inputTradecodeLl.setVisibility(View.GONE);
                    }
                }
            }
        });

        inputTradecodeBt.setOnClickListener(this);

        //发票使用控件
        fapiaoGetRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    myfapiaoLl.setVisibility(View.VISIBLE);
                    ifGetFapiao = true;
                    myfapiaoTv.setText(myFapiao.getInv_describe());
                }
                else {
                    myfapiaoLl.setVisibility(View.GONE);
                    ifGetFapiao = false;
                }
            }
        });

        commitOrderTv.setOnClickListener(this);

        changeMyfapiaoIb.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {

        if((!ifgetorder) && (v.getId()!=R.id.order_confirm_goback_ib))
        {
            return;
        }

        switch (v.getId()) {
            case R.id.order_confirm_goback_ib:
                finish();
                break;
            case R.id.order_changeinfo_ib://修改用户收货地址
            case R.id.no_address_ll://无地址时设置新用户收货地址
                Intent addressInt = new Intent(this,OrderAddressActivity.class);
                addressInt.putExtra("AddressId",myAddress.getAddress_id());
                startActivityForResult(addressInt,2);
                break;
            case R.id.use_xilinbi_bt:
                //修改希霖币个数
                useXilinBi();
                break;
            case R.id.commit_order_tv:
                commitOrder();
                break;
            case R.id.input_tradecode_bt:
                //验证支付密码
                useMemberMoney();
                break;
            case R.id.change_myfapiao_ib:
                Intent fapiaoInt = new Intent(this,FaPiaoActivity.class);
                fapiaoInt.putExtra("InvId", myFapiao.getInv_id());
                startActivityForResult(fapiaoInt,1);
                break;
            default:
                break;
        }
    }

    private void useMemberMoney() {
        String inputCode = inputTradecodeEt.getText().toString();
        confirmCode(inputCode);
    }

    private void useXilinBi() {
        set_xlb_num = FormatConfirm.stringToInt(inputXilinbiEt.getText().toString());
        if (set_xlb_num > xinlinbi_max) {
            Toast.makeText(getApplicationContext(), "希霖币个数超出可用范围！", Toast.LENGTH_LONG).show();
            inputXilinbiEt.setText(String.valueOf(xinlinbi_max));
            set_xlb_num = xinlinbi_max;
            return;
        }
        order_total_money += last_xilinbi_money;
        xlb_dis_money = set_xlb_num / xlb_dis;
        last_xilinbi_money = xlb_dis_money;
        xilinbiMoneyEt.setText("抵扣：￥" + xlb_dis_money);
        order_total_money -= xlb_dis_money;
        orderconfirmAtlastPriceTv.setText("￥" + order_total_money);
    }

    private void getGoodsList() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_buy&op=buy_step1";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        Log.i("zhangxiaoxidebug","key="+loginKey);
        params.addBodyParameter("cart_id", cart_id);
        Log.i("zhangxiaoxidebug","cart_id="+cart_id);
        params.addBodyParameter("ifcart", ifcart);
        Log.i("zhangxiaoxidebug","ifcart="+ifcart);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "商品查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "detail_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");

                            //地址处理部分
                            String myaddress = jsObjectDatas.getString("address_info");
                            if (myaddress.length() > 20) {
                                JSONObject jsObjectAddress = new JSONObject(myaddress);
                                String address_id = jsObjectAddress.getString("address_id");
                                String member_id = jsObjectAddress.getString("member_id");
                                String true_name = jsObjectAddress.getString("true_name");
                                String area_id = jsObjectAddress.getString("area_id");
                                String city_id = jsObjectAddress.getString("city_id");
                                String area_info = jsObjectAddress.getString("area_info");
                                String address = jsObjectAddress.getString("address");
                                String mob_phone = jsObjectAddress.getString("mob_phone");
                                String tel_phone = jsObjectAddress.getString("tel_phone");
                                int is_default = jsObjectAddress.getInt("is_default");
                                String dlyp_id = jsObjectAddress.getString("dlyp_id");

                                myAddress = new AddressBean.DatasBean.AddressListBean(address, address_id, area_id, area_info, city_id, dlyp_id, is_default, member_id, mob_phone, tel_phone, true_name);
                                orderUseradressLl.setVisibility(View.VISIBLE);
                                noAddressLl.setVisibility(View.GONE);
                                orderUsernameTv.setText(true_name);
                                if (!mob_phone.isEmpty()) {
                                    orderUserphoneTv.setText(mob_phone);
                                } else {
                                    orderUserphoneTv.setText(tel_phone);
                                }
                                orderUseradressTv.setText(area_info + address);
                            } else {
                                myAddress = new AddressBean.DatasBean.AddressListBean("", "noaddress", "", "", "", "", 0, "", "", "", "");
                                orderUseradressLl.setVisibility(View.GONE);
                                noAddressLl.setVisibility(View.VISIBLE);
                            }

                            //付款方式
                            offpay_hash = jsObjectDatas.getString("offpay_hash");
                            offpay_hash_batch = jsObjectDatas.getString("offpay_hash_batch");

                            //希霖币处理部分
                            max_use_xlb = jsObjectDatas.getInt("max_use_xlb");
                            member_xlb = jsObjectDatas.getInt("member_xlb");
                            xlb_dis = jsObjectDatas.getInt("xlb_dis");
                            if (max_use_xlb <= member_xlb) {
                                xinlinbi_max = max_use_xlb;
                            } else {
                                xinlinbi_max = member_xlb;
                            }
                            if (xinlinbi_max > 0 ) {
                                xilinbiPaynumRb.setVisibility(View.VISIBLE);
                                xilinbiPaynumRb.setText("使用希霖币抵扣（您有" + member_xlb + "个，可用" + max_use_xlb + "个）");
                                xlb_dis_money = (float)xinlinbi_max / xlb_dis;
                                inputXilinbiEt.setText(String.valueOf(xinlinbi_max));
                                xilinbiMoneyEt.setText("抵扣：￥" + xlb_dis_money);
                            } else {
                                xilinbiPaynumRb.setVisibility(View.GONE);
                            }

                            //充值卡处理部分
                            String cardMoney = jsObjectDatas.getString("available_rc_balance");
                            if(cardMoney==null||cardMoney.isEmpty()||cardMoney.equals("null"))
                            {
                                available_rc_balance = 0;
                            }
                            else
                            {
                                available_rc_balance = FormatConfirm.stringToFloat(cardMoney);
                            }
                            if (available_rc_balance > 0) {
                                chargecardPaynumRb.setVisibility(View.VISIBLE);
                                chargecardPaynumRb.setText("使用充值卡（可用金额：" + available_rc_balance + "元）");
                            } else {
                                chargecardPaynumRb.setVisibility(View.GONE);
                            }

                            //预付卡处理部分
                            String amountMoney = jsObjectDatas.getString("available_predeposit");
                            if(amountMoney==null||amountMoney.isEmpty()||amountMoney.equals("null"))
                            {
                                available_predeposit = 0;
                            }
                            else
                            {
                                available_predeposit = FormatConfirm.stringToFloat(amountMoney);
                            }

                            if (available_predeposit > 0) {
                                accountmoneyPaynumRb.setVisibility(View.VISIBLE);
                                accountmoneyPaynumRb.setText("使用预付卡（可用金额：" + available_predeposit + "元）");
                            } else {
                                accountmoneyPaynumRb.setVisibility(View.GONE);
                            }

                            //支付方式处理  需要在希霖币、充值卡和预存款之后处理
                            ifshow_offpay = jsObjectDatas.getString("ifshow_offpay");
                            if (ifshow_offpay.equals("true")) {
                                payOfflineRb.setVisibility(View.VISIBLE);
                                payOfflineView.setVisibility(View.VISIBLE);
                            } else {
                                payOfflineRb.setVisibility(View.GONE);
                                payOfflineView.setVisibility(View.GONE);
                            }

                            payOnlineRb.setChecked(true);

                            //发票处理部分
                            vat_hash = jsObjectDatas.getString("vat_hash");
                            String inv_info = jsObjectDatas.getString("inv_info");
                            if(inv_info.length()>20)
                            {
                                JSONObject jsobjectInv_info = new JSONObject(inv_info);
                                String inv_id = jsobjectInv_info.getString("inv_id");
                                String inv_title = jsobjectInv_info.getString("inv_title");
                                String inv_content = jsobjectInv_info.getString("inv_content");
                                String content = jsobjectInv_info.getString("content");
                                String inv_company = jsobjectInv_info.getString("inv_company");
                                myFapiao = new FaPiaoBean(inv_id, inv_title, inv_content, content, inv_company);
                            }
                            else
                            {
                                myFapiao = new FaPiaoBean("nofapiao", "", "", "请设置发票信息", "");
                            }

                            freight_hash = jsObjectDatas.getString("freight_hash");

                            String yunfeiContent = jsObjectDatas.getString("content");
                            if (yunfeiContent == null || yunfeiContent.isEmpty() || yunfeiContent.equals("null"))
                            {

                            }
                            else
                            {
                                List<ParamsBean> yunfeiList = FormatConfirm.getParameters(yunfeiContent);
                                yunfeiHash.clear();
                                for(int i=0;i<yunfeiList.size();i++)
                                {
                                    ParamsBean storeYunfei = yunfeiList.get(i);
                                    yunfeiHash.put(storeYunfei.getParamsId(),storeYunfei.getParamsKey());
                                }
                            }

                            //商品处理部分
                            JSONArray jsArrayStore = jsObjectDatas.getJSONArray("store_cart_list");
                            for (int i = 0; i < jsArrayStore.length(); i++) {
                                JSONObject jsObjectStore = jsArrayStore.getJSONObject(i);
                                JSONArray jsArrayGoods = jsObjectStore.getJSONArray("goods_list");
                                List<OrderGoodsInBean> thegoodsList = new ArrayList<>();
                                String store_total_money = jsObjectStore.getString("store_goods_total");
                                String store_name = jsObjectStore.getString("store_name");
                                String freight = jsObjectStore.getString("freight");
                                String store_total_freight = "0";
                                String store_id = "";
                                for (int j = 0; j < jsArrayGoods.length(); j++) {
                                    JSONObject jsObjectGoods = jsArrayGoods.getJSONObject(j);
                                    String cart_id = jsObjectGoods.getString("cart_id");
                                    store_id = jsObjectGoods.getString("store_id");
                                    String rec_id=jsObjectGoods.optString("rec_id");

                                    String goods_id = jsObjectGoods.getString("goods_id");
                                    String goods_name = jsObjectGoods.getString("goods_name");
                                    String goods_image_url = jsObjectGoods.getString("goods_image_url");
                                    String goods_price = jsObjectGoods.getString("goods_price");
                                    String goods_num = jsObjectGoods.getString("goods_num");
                                    float goods_freight = 0;
                                    if(jsObjectGoods.has("goods_freight"))
                                    {
                                        goods_freight = FormatConfirm.stringToFloat(jsObjectGoods.getString("goods_freight"));
                                    }
                                    float goods_total = FormatConfirm.stringToFloat(jsObjectGoods.getString("goods_total"));
                                    Log.i("zhangxiaoxidebug","goods_freight = "+goods_freight);
                                    Log.i("zhangxiaoxidebug","store_total_freight = "+store_total_freight);
                                    thegoodsList.add(new OrderGoodsInBean(cart_id,rec_id, goods_id, goods_name, goods_image_url, goods_price, goods_num, goods_total, goods_freight));
                                }

                                //如果本店免运费的话，则在此处将运费置0
                                if (freight.equals("0"))
                                {
                                    store_total_freight = "0";
                                }
                                else
                                {
                                    if(yunfeiHash.containsKey(store_id))
                                    {
                                        store_total_freight = yunfeiHash.get(store_id);
                                    }
                                    else
                                    {
                                        store_total_freight = "0";
                                    }
                                }

                                //满即送处理部分
                                ManSongBean storeManSong = null;
                                String mansongStr = jsObjectStore.getString("store_mansong_rule_list");
                                if(mansongStr.contains("rule_id"))
                                {
                                    JSONObject jsObjectMS = jsObjectStore.getJSONObject("store_mansong_rule_list");
                                    String rule_id = jsObjectMS.getString("rule_id");
                                    String mansong_id = jsObjectMS.getString("mansong_id");
                                    String price = jsObjectMS.getString("price");
                                    String discount = jsObjectMS.getString("discount");
                                    String mansong_goods_name = jsObjectMS.getString("mansong_goods_name");
                                    String goods_id = jsObjectMS.getString("goods_id");
                                    String mansong_name = jsObjectMS.getString("mansong_name");
                                    String start_time = jsObjectMS.getString("start_time");
                                    String end_time = jsObjectMS.getString("end_time");
                                    String mandesc = jsObjectMS.getString("desc");
                                    storeManSong = new ManSongBean(rule_id,mansong_id,price,discount,mansong_goods_name,goods_id,mansong_name,start_time,end_time,mandesc);
                                }
                                else
                                {
                                    storeManSong = new ManSongBean("","","-1","0","","","","0","0","");
                                }

                                //优惠券处理部分
                                List<YouHuiQuanBean> myYHQList = new ArrayList<>();
                                JSONArray jsArrayYHQ = jsObjectStore.getJSONArray("store_voucher_list");

                                //如果本店铺有代金券，则首先添加一个不使用代金券的选项
                                if(jsArrayYHQ.length()>0)
                                {
                                    myYHQList.add(new YouHuiQuanBean("0", "0", "0", "不使用代金券", "不使用代金券", "0", "0", "0", "0", "0", "", "", "不使用代金券"));
                                }

                                for (int m = 0; m < jsArrayYHQ.length(); m++) {
                                    JSONObject jsObjectYHQ = jsArrayYHQ.getJSONObject(m);
                                    String voucher_id = jsObjectYHQ.getString("voucher_id");
                                    String voucher_code = jsObjectYHQ.getString("voucher_code");
                                    String voucher_t_id = jsObjectYHQ.getString("voucher_t_id");
                                    String voucher_title = jsObjectYHQ.getString("voucher_title");
                                    String voucher_desc = jsObjectYHQ.getString("voucher_desc");
                                    String voucher_start_date = jsObjectYHQ.getString("voucher_start_date");
                                    String voucher_end_date = jsObjectYHQ.getString("voucher_end_date");
                                    String voucher_price = jsObjectYHQ.getString("voucher_price");
                                    String voucher_limit = jsObjectYHQ.getString("voucher_limit");
                                    String voucher_store_id = jsObjectYHQ.getString("voucher_store_id");
                                    String voucher_state = jsObjectYHQ.getString("voucher_state");
                                    String voucher_active_date = jsObjectYHQ.getString("voucher_active_date");
                                    String desc = jsObjectYHQ.getString("desc");
                                    myYHQList.add(new YouHuiQuanBean(voucher_id, voucher_code, voucher_t_id, voucher_title, voucher_desc, voucher_start_date, voucher_end_date, voucher_price, voucher_limit, voucher_store_id, voucher_state, voucher_active_date, desc));
                                }

                                //本店商品总价
                                float store_money_calcu =  FormatConfirm.stringToFloat(store_total_money);
                                //本店总运费
                                float store_freight_calcu =  FormatConfirm.stringToFloat(store_total_freight);
                                //本店总计
                                store_money_calcu += store_freight_calcu;
                                //店铺满即送活动处理判断
                                float mansongPrice = FormatConfirm.stringToFloat(storeManSong.getMansong_price());
                                float mansongDiscount = FormatConfirm.stringToFloat(storeManSong.getMansong_discount());
                                Long current = System.currentTimeMillis()/1000;
                                Long startTime = Long.parseLong(storeManSong.getStart_time());
                                Long endTime = Long.parseLong(storeManSong.getEnd_time());
                                if(mansongPrice>0 && store_money_calcu>=mansongPrice && current>=startTime && current<=endTime)
                                {
                                    store_money_calcu -=mansongDiscount;
                                    storeManSong.setIfCanUse(true);
                                }

                                //订单总计
                                order_total_money += store_money_calcu;
                                myGoodsList.add(new OrderGoodsOutBean(store_id, store_name, store_total_money,
                                        freight, "", myYHQList,storeManSong,store_money_calcu, store_freight_calcu,
                                        thegoodsList));
                            }

                            myGoodsAdapter.notifyDataSetChanged();
                            ScrollListViewDisplay.setListViewHeightBasedOnChildren(orderStoresListview);
                            orderconfirmAtlastPriceTv.setText("￥" + order_total_money);
                            ifgetorder = true;

                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "商品查询失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    //验证支付密码
    private void confirmCode(String code) {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_buy&op=check_password";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        params.addBodyParameter("password", code);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String  result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "certify_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "支付密码验证失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            }
                            else
                            {
                                String datas = jsObjectCode.getString("datas");
                                if(datas.equals("1"))
                                {
                                    codeCertify = true;
                                    Toast.makeText(getApplicationContext(), "密码正确", Toast.LENGTH_LONG).show();
                                }
                                else {
                                    JSONObject jsobjectDatas = new JSONObject(datas);
                                    String errors = jsobjectDatas.getString("error");
                                    Toast.makeText(getApplicationContext(), errors, Toast.LENGTH_LONG).show();
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "支付密码验证失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    //修改收货地址
    private void changeAddress() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_buy&op=change_address";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        Log.i("zhangxiaoxidebug","key="+loginKey);
        params.addBodyParameter("freight_hash", freight_hash);
        Log.i("zhangxiaoxidebug","freight_hash="+freight_hash);
        params.addBodyParameter("city_id", changedAddressTemp.getCity_id());
        Log.i("zhangxiaoxidebug","city_id="+changedAddressTemp.getCity_id());
        params.addBodyParameter("area_id", changedAddressTemp.getArea_id());
        Log.i("zhangxiaoxidebug","area_id="+changedAddressTemp.getArea_id());

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String  result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "changeAddress_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "地址修改失败，请检查网络设置！", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                String datas = jsObjectCode.getString("datas");
                                if(datas.contains("success"))
                                {
                                    JSONObject jsObjectDatas = new JSONObject(datas);
                                    offpay_hash = jsObjectDatas.getString("offpay_hash");
                                    offpay_hash_batch = jsObjectDatas.getString("offpay_hash_batch");
                                    allow_offpay = jsObjectDatas.getString("allow_offpay");

                                    if (allow_offpay.equals("1")) {
                                        payOfflineRb.setVisibility(View.VISIBLE);
                                        payOfflineView.setVisibility(View.VISIBLE);
                                    } else {
                                        payOfflineRb.setVisibility(View.GONE);
                                        payOfflineView.setVisibility(View.GONE);
                                    }
                                    payOnlineRb.setChecked(true);

                                    myAddress = changedAddressTemp;
                                    orderUseradressLl.setVisibility(View.VISIBLE);
                                    noAddressLl.setVisibility(View.GONE);
                                    orderUsernameTv.setText(myAddress.getTrue_name());
                                    if (!myAddress.getMob_phone().isEmpty()) {
                                        orderUserphoneTv.setText(myAddress.getMob_phone());
                                    } else {
                                        orderUserphoneTv.setText(myAddress.getTel_phone());
                                    }
                                    orderUseradressTv.setText(myAddress.getArea_info() + myAddress.getAddress());

                                    //运费修改
                                    String yunfeiContent = jsObjectDatas.getString("content");
                                    if (yunfeiContent == null || yunfeiContent.isEmpty() || yunfeiContent.equals("null"))
                                    {

                                    }
                                    else
                                    {
                                        List<ParamsBean> yunfeiList = FormatConfirm.getParameters(yunfeiContent);
                                        yunfeiHash.clear();
                                        for(int i=0;i<yunfeiList.size();i++)
                                        {
                                            ParamsBean storeYunfei = yunfeiList.get(i);
                                            yunfeiHash.put(storeYunfei.getParamsId(),storeYunfei.getParamsKey());
                                        }
                                    }

                                    order_total_money = 0;
                                    for(int i=0;i<myGoodsList.size();i++)
                                    {
                                        OrderGoodsOutBean thegood = myGoodsList.get(i);
                                        //如果本店免运费的话，则在此处将运费置0
                                        String storeID = thegood.getStore_Id();
                                        float store_total_money = FormatConfirm.stringToFloat(thegood.getStore_goods_total());
                                        float newFreight = 0;
                                        //是否需要运费的标识 0代表免运费
                                        String freight = thegood.getFreight();
                                        if (freight.equals("0"))
                                        {
                                            newFreight = 0;
                                        }
                                        else
                                        {
                                            if (yunfeiHash.containsKey(storeID)) {
                                                newFreight = FormatConfirm.stringToFloat(yunfeiHash.get(storeID));
                                            }
                                            else
                                            {
                                                newFreight = thegood.getGoods_total_freight();
                                            }
                                        }

                                        thegood.setGoods_total_freight(newFreight);
                                        float storetotal = store_total_money+newFreight;
                                        order_total_money += storetotal;
                                        thegood.setGoods_total_money(storetotal);
                                    }
                                    myGoodsAdapter.notifyDataSetChanged();
                                    ScrollListViewDisplay.setListViewHeightBasedOnChildren(orderStoresListview);
                                    orderconfirmAtlastPriceTv.setText("￥" + order_total_money);
                                    setAddressDefault();
                                }
                                else {
                                    JSONObject jsobjectDatas = new JSONObject(datas);
                                    String errors = jsobjectDatas.getString("error");
                                    Toast.makeText(getApplicationContext(), errors, Toast.LENGTH_LONG).show();
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "支付密码验证失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void setAddressDefault() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=default_addrss&member_id=" +
                MainActivity.myLogin.getMemberid() + "&id=" + myAddress.getAddress_id() + "&is_default=1";
        Log.i("zhangxiaoxidebug", "setAddressDefault url=" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "defaultAddress =" + resultinfo);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug","设置默认地址失败！");
                    }
                });
    }

    private void commitOrder() {
        if(myAddress.getAddress_id().equals("noaddress"))
        {
            Toast.makeText(getApplicationContext(),"您的收货地址还没有设置！",Toast.LENGTH_LONG).show();
            return;
        }
        if(ifGetFapiao && myFapiao.getInv_id().equals("nofapiao"))
        {
            Toast.makeText(getApplicationContext(),"您还需要填写发票内容！",Toast.LENGTH_LONG).show();
            return;
        }

        if(useCharge || useAccount>0)
        {
            if(!codeCertify)
            {
                Toast.makeText(getApplicationContext(),"请验证您的支付密码！",Toast.LENGTH_LONG).show();
                return;
            }
        }
        String url = "http://www.xilingou.com/mobile/index.php?act=member_buy&op=buy_step2";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        Log.i("zhangxiaoxidebug","loginKey="+loginKey);
        params.addBodyParameter("ifcart", ifcart);
        Log.i("zhangxiaoxidebug","ifcart="+ifcart);
        params.addBodyParameter("cart_id", cart_id);
        Log.i("zhangxiaoxidebug","cart_id="+cart_id);
        params.addBodyParameter("address_id", myAddress.getAddress_id());
        Log.i("zhangxiaoxidebug","address_id="+myAddress.getAddress_id());
        params.addBodyParameter("vat_hash", vat_hash);
        Log.i("zhangxiaoxidebug","vat_hash="+vat_hash);
        params.addBodyParameter("offpay_hash", offpay_hash);
        Log.i("zhangxiaoxidebug","offpay_hash="+offpay_hash);
        params.addBodyParameter("offpay_hash_batch", offpay_hash_batch);
        Log.i("zhangxiaoxidebug","offpay_hash_batch="+offpay_hash_batch);
        params.addBodyParameter("pay_name", pay_name);
        Log.i("zhangxiaoxidebug","pay_name="+pay_name);
        params.addBodyParameter("invoice_id", myFapiao.getInv_id());
        Log.i("zhangxiaoxidebug","myFapiao.getInv_id()="+myFapiao.getInv_id());
        params.addBodyParameter("voucher", getYHQ());
        Log.i("zhangxiaoxidebug","getYHQ()="+getYHQ());
        params.addBodyParameter("pd_pay",String.valueOf(useAccount));
        Log.i("zhangxiaoxidebug","String.valueOf(useAccount)="+String.valueOf(useAccount));
        params.addBodyParameter("password",inputTradecodeEt.getText().toString());
        Log.i("zhangxiaoxidebug","password="+inputTradecodeEt.getText().toString());
        String message = getMessage();
        if(message.length()>0)
        {
            params.addBodyParameter("pay_message", message);
        }
        if(set_xlb_num>0)
        {
            params.addBodyParameter("useXlb","1");
        }
        else
        {
            params.addBodyParameter("useXlb","0");
        }
        params.addBodyParameter("use_xlb_num",String.valueOf(set_xlb_num));
        Log.i("zhangxiaoxidebug","use_xlb_num="+String.valueOf(set_xlb_num));
        //params.addBodyParameter("fcode", "");

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String  result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "certify_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "订单提交失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            }
                            else
                            {
                                String datas = jsObjectCode.getString("datas");
                                if(datas.contains("pay_sn"))
                                {
                                    JSONObject jsobjectPaysn = new JSONObject(datas);
                                    pay_sn = jsobjectPaysn.getString("pay_sn");
                                    Intent payInt= new Intent(OrderConfirmActivity.this, WaitPayDetailActivity.class);
                                    payInt.putExtra("PaySn",pay_sn);
                                    payInt.putExtra("orderIdString", "");
                                    startActivity(payInt);
                                    //订单提交成功后，关闭掉此页面
                                    setResult(1);
                                    finish();
                                }
                                else
                                {
                                    JSONObject jsobjectDatas = new JSONObject(datas);
                                    String errors = jsobjectDatas.getString("error");
                                    Toast.makeText(getApplicationContext(), errors, Toast.LENGTH_LONG).show();
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "订单提交失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private String getMessage() {


        StringBuffer sayBuffer = new StringBuffer();

        for(int i = 0;i<myGoodsList.size();i++)
        {
            String sayInfo = myGoodsList.get(i).getSaySomething();


            String storeId = myGoodsList.get(i).getStore_Id();

            if(!sayInfo.isEmpty())
            {
                sayBuffer.append(storeId+"|"+sayInfo+",");
            }
        }
        if(sayBuffer.length()>0)
        {
            sayBuffer.deleteCharAt(sayBuffer.length() - 1);
        }

        Log.i("zhangxiaoxidebug","sayBuffer = "+sayBuffer.toString());
        return sayBuffer.toString();
    }

    private String getYHQ()
    {
        String selectedYHQ = "";

        for(int i=0,m=0;i<myGoodsList.size();i++)
        {
            //本店铺存在优惠券，并且选中的优惠券不是位置0的那一项
            if(myGoodsList.get(i).getYhqList().size()>0 && myGoodsList.get(i).getSelectetYHQ()>0 )
            {
                String storeId = myGoodsList.get(i).getStore_Id();
                String yhqID = myGoodsList.get(i).getYhqList().get(myGoodsList.get(i).getSelectetYHQ()).getVoucher_t_id();
                String yhqPrice = myGoodsList.get(i).getYhqList().get(myGoodsList.get(i).getSelectetYHQ()).getVoucher_price();
                String tempStr = "";
                if(m==0)
                {
                    tempStr = yhqID+"|"+storeId+"|"+yhqPrice;
                }
                else
                {
                    tempStr = selectedYHQ + ","+yhqID+"|"+storeId+"|"+yhqPrice;
                }
                m ++;
                selectedYHQ = tempStr;
            }
        }

        return  selectedYHQ;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == 1)
        {
            switch (requestCode)
            {
                case 1:  //修改发票
                    myFapiao = (FaPiaoBean)data.getBundleExtra("FapiaoBundle").getSerializable("InvFapiao");
                    myfapiaoTv.setText(myFapiao.getInv_describe());
                    break;
                case 2:  //修改收货地址
                    changedAddressTemp = (AddressBean.DatasBean.AddressListBean) data.getBundleExtra("AddressBundle").getSerializable("SelectedAddress");
                    changeAddress();
                    break;
                default:
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
